package ui;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import ui.CreateEditTaskDialog.Status;
import ui.CreateEditTaskDialog.TaskData;
import ui.ItemPanel2.TaskUpdatedListener;
import control.UITaskManagerBridge;
import control.UITaskManagerBridge.OrderBy;
import entity.general.MinTime;
import entity.general.SecTime;
import entity.general.Time;
import entity.main.ObjectiveTaskManager;
import entity.main.Task;
import entity.main.Task.TaskType;
import java.awt.Toolkit;

public class EventViewFrame5 extends JFrame implements ActionListener, TaskUpdatedListener {

	private JPanel contentPane;
	private JTextField searchTextField;

	Map <String, ItemPanel2ListPanel> itemPanelListPanels = new HashMap<>();
	Map <ItemPanel2, ItemPanel2ListPanel> itemPanelToItemPanelListPanel = new HashMap<>();
	
	private Task currentlySelectedTask;
	private ItemPanel2 currentlySelectedTaskItemPanel;
	
	JPanel scrollPanePanel;
	
	JPanel listViewFillPanel = new JPanel();
	private JMenuItem NewMenuItem;
	private JMenuItem LoadMenuItem;
	private JMenuItem SaveMenuItem;
	private JMenuItem SaveAsMenuItem;
	private UITaskManagerBridge taskManagerBridge;
	private JRadioButton rdbtnName;
	private JRadioButton rdbtnTime;
//	private JRadioButton rdbtnCategory;
	private JButton btnNewTask;
	private DetailsPanel2 detailsPanel;
	
	File lastUsedSaveLoadDir = new File("./ActivlySaves");
	private File lastUsedSaveFile;
	private JPanel panel_1;
	private JPanel panel_2;
	private JButton startTimerButton;
	private JButton stopTimerButton;
	private JButton addTimerTimeToTaskButton;
	private JTextField effectivenessTextField;
	private JLabel lblEffectiveness;
	private JLabel label;
	private JLabel lblTotal;
	private JTextField timerTimeTextField;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					EventViewFrame5 frame = new EventViewFrame5(new UITaskManagerBridge());
					frame.setVisible(true);					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	Timer timer = new Timer();
	private JButton pauseTimerButton;
	private JCheckBox chckbxPinned;
	private JCheckBox chckbxCompleted;

	public class TimerListener implements ActionListener
	{

		@Override
		public void actionPerformed(ActionEvent e) {
			if(e.getSource() == startTimerButton)
			{
				EventViewFrame5.this.timer.startTimer();
			}
			else if(e.getSource() == stopTimerButton)
			{
				EventViewFrame5.this.timer.stopTimer();				
			}
			else if(e.getSource() == addTimerTimeToTaskButton)
			{
				EventViewFrame5.this.addTimerTimeToSelectedTask();
				EventViewFrame5.this.timer.stopTimer();				
			}
			else if(e.getSource() == pauseTimerButton)
			{
				EventViewFrame5.this.timer.pauseTimer();
			}			
		}
		
	}
	
	public class Timer implements Runnable
	{
		DateTime startDateTime;
		boolean timerActive = false;
		Thread curTimerThread = null;
		
		SecTime timeToAdd = new SecTime(0,0,0);
//		SecTime timeToAdd = new SecTime(0,0,0);
		boolean isPaused = false;
		
		public Timer()
		{
			
		}
		
		public void startTimer()
		{
			unsetTimer();
			System.out.println("Timer start active");
			startDateTime = DateTime.now();
			if(!timerActive)
			{
				timerActive = true;
				curTimerThread = new Thread(this);
				curTimerThread.start();
			}
//			timeToAdd = new SecTime(0,10,0);
		}
		
		public void stopTimer()
		{
			unsetTimer();
		}
		
		public void unsetTimer()
		{
			startDateTime = null;
			timerActive = false;
			isPaused = false;
			EventViewFrame5.this.resetTimerFieldToZero();
			timeToAdd = new SecTime(0,0,0);			
		}

		public void pauseTimer() {
			//unpause
			if(isPaused)
			{
				startDateTime = DateTime.now();
				setTimerBackgroundEnabled();
			}
			//pause
			else
			{
				setTimerBackgroundDisabled();
				int seconds = (int)(DateTime.now().getMillis() - startDateTime.getMillis()) / 1000;
				timeToAdd = timeToAdd.add(new SecTime(seconds));
			}
			isPaused = !isPaused;			
		}
		
		private void setTimerBackgroundDisabled()
		{
			EventViewFrame5.this.timerTimeTextField.setBackground(new Color(255, 100, 100));
			EventViewFrame5.this.timerTimeTextField.repaint();			
		}

		private void setTimerBackgroundEnabled()
		{
			EventViewFrame5.this.timerTimeTextField.setBackground(new Color(240, 240, 240));
			EventViewFrame5.this.timerTimeTextField.repaint();
		}

		@Override
		public void run() {
			while(timerActive)
			{				
//				System.out.println("Timer is active");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if(!timerActive)
					break;
				if(isPaused)
					continue;
				
				int seconds = (int)(DateTime.now().getMillis() - startDateTime.getMillis()) / 1000;
				SecTime updateTime = timeToAdd;
				updateTime = updateTime.add(new SecTime(seconds));
//				EventViewFrame5.this.updateTimerField(updateTime.toMinTime());
				EventViewFrame5.this.updateTimerField(updateTime);
//				System.out.println("Update complete");
			}
		}

		public MinTime getMinTime() {
			SecTime updateTime = timeToAdd;
			int seconds = (int)(DateTime.now().getMillis() - startDateTime.getMillis()) / 1000;
			updateTime = updateTime.add(new SecTime(seconds));
			return updateTime.toMinTime();
		}		
	}
	
//	public static void main(String[] args) {
//		EventQueue.invokeLater(new Runnable() {
//			public void run() {
//				try {
//					EventViewFrame3 frame = new EventViewFrame3();
//					frame.setVisible(true);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		});
//	}

	/**
	 * Create the frame.
	 */
	public EventViewFrame5(UITaskManagerBridge uiTMB) {
		setIconImage(Toolkit.getDefaultToolkit().getImage(EventViewFrame5.class.getResource("/images/ActivlyIcon.png")));
		taskManagerBridge = uiTMB;
		
		setTitle("Activly");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 738, 384);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu FileMenu = new JMenu("File");
		menuBar.add(FileMenu);
		
		NewMenuItem = new JMenuItem("New");
		FileMenu.add(NewMenuItem);
		
		LoadMenuItem = new JMenuItem("Load");
		FileMenu.add(LoadMenuItem);
		
		SaveMenuItem = new JMenuItem("Save");
		FileMenu.add(SaveMenuItem);
		
		SaveAsMenuItem = new JMenuItem("SaveAs");
		FileMenu.add(SaveAsMenuItem);
		
		NewMenuItem.addActionListener(this);
		LoadMenuItem.addActionListener(this);
		SaveMenuItem.addActionListener(this);
		SaveAsMenuItem.addActionListener(this);
		

		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		GridBagLayout gbl_contentPane = new GridBagLayout();
		gbl_contentPane.columnWidths = new int[] {500, 0};
		gbl_contentPane.rowHeights = new int[] {0, 217};
		gbl_contentPane.columnWeights = new double[]{0.0, 1.0};
		gbl_contentPane.rowWeights = new double[]{0.0, 1.0};
		contentPane.setLayout(gbl_contentPane);
		
		JPanel controlsPanel = new JPanel();
		GridBagConstraints gbc_controlsPanel = new GridBagConstraints();
		gbc_controlsPanel.fill = GridBagConstraints.BOTH;
		gbc_controlsPanel.anchor = GridBagConstraints.WEST;
		gbc_controlsPanel.gridwidth = 2;
		gbc_controlsPanel.insets = new Insets(0, 0, 5, 0);
		gbc_controlsPanel.gridx = 0;
		gbc_controlsPanel.gridy = 0;
		contentPane.add(controlsPanel, gbc_controlsPanel);
		GridBagLayout gbl_controlsPanel = new GridBagLayout();
		gbl_controlsPanel.columnWidths = new int[]{115, 0};
		gbl_controlsPanel.rowHeights = new int[]{23, 0, 0};
		gbl_controlsPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gbl_controlsPanel.rowWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
		controlsPanel.setLayout(gbl_controlsPanel);
		
		panel_1 = new JPanel();
		GridBagConstraints gbc_panel_1 = new GridBagConstraints();
		gbc_panel_1.insets = new Insets(0, 0, 5, 0);
		gbc_panel_1.fill = GridBagConstraints.BOTH;
		gbc_panel_1.gridx = 0;
		gbc_panel_1.gridy = 0;
		controlsPanel.add(panel_1, gbc_panel_1);
		
		btnNewTask = new JButton("New Task");
		panel_1.add(btnNewTask);
		
		JLabel lblSearch = new JLabel("Search");
		panel_1.add(lblSearch);
		
		searchTextField = new JTextField();
		panel_1.add(searchTextField);
		searchTextField.setColumns(15);
		
		JLabel lblOrderBy = new JLabel("Order by:");
		panel_1.add(lblOrderBy);
		
		ButtonGroup group = new ButtonGroup();
		
		rdbtnName = new JRadioButton("Name");
		panel_1.add(rdbtnName);
		rdbtnName.setSelected(true);
		group.add(rdbtnName);
		
		rdbtnTime = new JRadioButton("Time");
		panel_1.add(rdbtnTime);
		group.add(rdbtnTime);
		
//		rdbtnCategory = new JRadioButton("Category");
//		panel_1.add(rdbtnCategory);
		
		panel_2 = new JPanel();
		GridBagConstraints gbc_panel_2 = new GridBagConstraints();
		gbc_panel_2.fill = GridBagConstraints.BOTH;
		gbc_panel_2.gridx = 0;
		gbc_panel_2.gridy = 1;
		controlsPanel.add(panel_2, gbc_panel_2);
		
		startTimerButton = new JButton("Start");
		panel_2.add(startTimerButton);
		
		pauseTimerButton = new JButton("Pause");
		panel_2.add(pauseTimerButton);
		
		stopTimerButton = new JButton("Stop");
		panel_2.add(stopTimerButton);
		
		lblEffectiveness = new JLabel("Eff:");
		panel_2.add(lblEffectiveness);
		
		effectivenessTextField = new JTextField();
		effectivenessTextField.setText("100");
		panel_2.add(effectivenessTextField);
		effectivenessTextField.setColumns(3);
		
		label = new JLabel("%");
		panel_2.add(label);
		
		lblTotal = new JLabel("Total:");
		panel_2.add(lblTotal);
		
		timerTimeTextField = new JTextField();
		timerTimeTextField.setEditable(false);
		timerTimeTextField.setText("00:00:00");
		panel_2.add(timerTimeTextField);
		timerTimeTextField.setColumns(6);
		
		addTimerTimeToTaskButton = new JButton("Add");
		panel_2.add(addTimerTimeToTaskButton);
		
		TimerListener timerListener = new TimerListener();
		
		addTimerTimeToTaskButton.addActionListener(timerListener);
		startTimerButton.addActionListener(timerListener);
		stopTimerButton.addActionListener(timerListener);
		pauseTimerButton.addActionListener(timerListener);
		
//		group.add(rdbtnCategory);
//		rdbtnCategory.addActionListener(this);
		
		chckbxPinned = new JCheckBox("Pinned");
		panel_1.add(chckbxPinned);
		
		chckbxCompleted = new JCheckBox("Completed");
		chckbxCompleted.setSelected(true);
		panel_1.add(chckbxCompleted);
		rdbtnTime.addActionListener(this);
		
		
		chckbxCompleted.addActionListener(this);
		chckbxPinned.addActionListener(this);
		
				rdbtnName.addActionListener(this);
		searchTextField.addKeyListener(new KeyAdapter()
		{
			public void keyReleased(KeyEvent ke)
			{
				reloadDataFromTaskManagerBridge();
			}
		});
		btnNewTask.addActionListener(this);
				
		JPanel listPanel = new JPanel();
		GridBagConstraints gbc_listPanel = new GridBagConstraints();
		gbc_listPanel.fill = GridBagConstraints.BOTH;
		gbc_listPanel.insets = new Insets(0, 0, 0, 5);
		gbc_listPanel.gridx = 0;
		gbc_listPanel.gridy = 1;
		contentPane.add(listPanel, gbc_listPanel);
		listPanel.setLayout(new GridLayout(0, 1, 0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		listPanel.add(scrollPane);
		
		scrollPanePanel = new JPanel();
		scrollPane.setViewportView(scrollPanePanel);
		GridBagLayout gbl_scrollPanePanel = new GridBagLayout();
		gbl_scrollPanePanel.columnWidths = new int[] {476, 0};
		gbl_scrollPanePanel.rowHeights = new int[] {76, 0};
		gbl_scrollPanePanel.columnWeights = new double[]{1.0};
		gbl_scrollPanePanel.rowWeights = new double[]{0.0, 1.0};
		scrollPanePanel.setLayout(gbl_scrollPanePanel);
		
		JPanel FillPanel = new JPanel();
		GridBagConstraints gbc_FillPanel = new GridBagConstraints();
		gbc_FillPanel.anchor = GridBagConstraints.SOUTH;
		gbc_FillPanel.insets = new Insets(0, 0, 0, 5);
		gbc_FillPanel.fill = GridBagConstraints.HORIZONTAL;
		gbc_FillPanel.gridx = 0;
		gbc_FillPanel.gridy = 1;
		scrollPanePanel.add(FillPanel, gbc_FillPanel);
		
		detailsPanel = new DetailsPanel2();
		GridBagConstraints gbc_detailsPanel = new GridBagConstraints();
		gbc_detailsPanel.fill = GridBagConstraints.BOTH;
		gbc_detailsPanel.gridx = 1;
		gbc_detailsPanel.gridy = 1;
		contentPane.add(detailsPanel, gbc_detailsPanel);
		
		reloadDataFromTaskManagerBridge();
	}
	
	public void addTimerTimeToSelectedTask() {
		System.out.println("Trying to add");
		if(currentlySelectedTask != null)
		{
			System.out.println("Selected task not null, adding");
			MinTime time = timer.getMinTime();
			if(!effectivenessTextField.getText().equals("100"))
			{
				time = time.multBy((float)Integer.valueOf(effectivenessTextField.getText())/100.0f);
			}
			currentlySelectedTask.addTimeSpent(time);
			if(currentlySelectedTaskItemPanel != null)
			{
				System.out.println("Panel not null, repainting");
				currentlySelectedTaskItemPanel.setFieldsFromTask();
				currentlySelectedTaskItemPanel.repaint();
				detailsPanel.resetDataFromTask();
				detailsPanel.repaint();
			}
		}
	}

	public void updateTimerField(Time time) {
		timerTimeTextField.setText(time.toString());
	}

	public void resetTimerFieldToZero() {
		timerTimeTextField.setText((new SecTime(0,0,0)).toString());
	}

	public void removeAllItemPanel2ListPanels()
	{
		scrollPanePanel.removeAll();
		scrollPanePanel.add(listViewFillPanel);
		scrollPanePanel.repaint();
	}
	
	public void addItemPanel2ListPanel(String name)
	{
		if(itemPanelListPanels.containsKey(name))
		{
			throw new RuntimeException("Already have panel called " + name);
		}
		else
		{
			scrollPanePanel.remove(listViewFillPanel);
			
			ItemPanel2ListPanel itemPanel2ListPanel = new ItemPanel2ListPanel(name, Color.gray, Color.white);
			GridBagLayout gridBagLayout = (GridBagLayout) itemPanel2ListPanel.getLayout();
			gridBagLayout.rowWeights = new double[]{1.0, 1.0};
			gridBagLayout.columnWeights = new double[]{0.0, 1.0};
	
			GridBagConstraints gbc_itemPanel2ListPanel = new GridBagConstraints();
			gbc_itemPanel2ListPanel.anchor = GridBagConstraints.NORTH;
			gbc_itemPanel2ListPanel.insets = new Insets(0, 0, 5, 5);
//			gbc_itemPanel2ListPanel.fill = GridBagConstraints.BOTH;
			gbc_itemPanel2ListPanel.fill = GridBagConstraints.HORIZONTAL;
			gbc_itemPanel2ListPanel.gridx = 0;
			gbc_itemPanel2ListPanel.gridy = itemPanelListPanels.size();
			
			scrollPanePanel.add(itemPanel2ListPanel, gbc_itemPanel2ListPanel);
			itemPanelListPanels.put(name, itemPanel2ListPanel);
			
			GridBagConstraints gbc_fillPanel = new GridBagConstraints();
			gbc_fillPanel.gridy = itemPanelListPanels.size()+1;
			gbc_fillPanel.fill = GridBagConstraints.BOTH;
			scrollPanePanel.add(listViewFillPanel, gbc_fillPanel);
		}
	}

	public void addTask(String itemPanelName, Task task)
	{
		if(!itemPanelListPanels.containsKey(itemPanelName))
		{
			throw new RuntimeException("Don't have " + itemPanelName);
		}
		else
		{
			ItemPanel2 itemPanel = new ItemPanel2(task);
			itemPanel.addTaskUpdatedListener(this);
			itemPanel.addMouseListener(new MouseAdapter()
			{
				public void mouseClicked(MouseEvent me)
				{
					Task task = ((ItemPanel2)me.getSource()).getTask();
					detailsPanel.setTask(task);
					currentlySelectedTask = task;
					currentlySelectedTaskItemPanel = ((ItemPanel2)me.getSource());
				}
			});
			itemPanelListPanels.get(itemPanelName).add(itemPanel);
			itemPanelToItemPanelListPanel.put(itemPanel, itemPanelListPanels.get(itemPanelName));
		}
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getSource() == NewMenuItem)
		{
			lastUsedSaveFile = null;
			taskManagerBridge.setObjectiveTaskManager(new ObjectiveTaskManager());
			reloadDataFromTaskManagerBridge();
		}
		else if(arg0.getSource() == LoadMenuItem)
		{
			if(!lastUsedSaveLoadDir.exists())
				lastUsedSaveLoadDir.mkdir();
			JFileChooser chooseFile = new JFileChooser(lastUsedSaveLoadDir);
			chooseFile.addChoosableFileFilter(
					new FileFilter()
					{
					    public boolean accept(File f)
					    {
					        if(f.isDirectory())
					        {
					            return true;
					        }
					        return f.getName().endsWith(".activly");
					    }
					 
					    public String getDescription()
					    {
					        return "Activly files (*.activly)";
					    }					
					}
			);
			int ret = chooseFile.showOpenDialog(this);
			if(ret == JFileChooser.APPROVE_OPTION)
			{
				File f = chooseFile.getSelectedFile();
				if(f.isFile())
				{
					try {
						taskManagerBridge.loadTaskData(f);
						lastUsedSaveLoadDir = f.getCanonicalFile();
						reloadDataFromTaskManagerBridge();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			else
			{
				//Ignore
			}
		}
		else if(arg0.getSource() == SaveMenuItem)
		{
			if(lastUsedSaveFile == null)
			{
				doSaveAs();
			}
			else
			{
				doSave();
			}
		}
		else if(arg0.getSource() == SaveAsMenuItem)
		{
			doSaveAs();
		}
		else if(arg0.getSource() == btnNewTask)
		{
			List <String> l = new ArrayList <>();
			l.add("Other");
			CreateEditTaskDialog ctDialog = new CreateEditTaskDialog(l);
			ctDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			ctDialog.setVisible(true);
			Status status = ctDialog.getStatus();
			System.out.println(ctDialog.getName() + ", " + status.name());
			
			if(status == Status.OK)
			{
				String name = ctDialog.getName();
				TaskType type = ctDialog.getTaskType();
				String parentObjectiveName = ctDialog.getCategoryName();
				LocalDate start = DateTime.now().toLocalDate();
				LocalDate deadline;
				if(ctDialog.hasDeadline())
				{
					deadline = ctDialog.getDeadlineDate();
				}
				else
					deadline = null;
				String description = ctDialog.getDescription();
				MinTime timeToSpend = ctDialog.getTime();
				
				//taskManagerBridge.createTask(name, type, parentObjectiveName, start, deadline, description, timeToSpend);
				taskManagerBridge.createTask(name, type, parentObjectiveName, start, deadline, description, timeToSpend);
				reloadDataFromTaskManagerBridge();
			}
		
		}
		else if(arg0.getSource() == rdbtnName || arg0.getSource() == rdbtnTime)// || arg0.getSource() == rdbtnCategory)
		{
			reloadDataFromTaskManagerBridge();			
		}
		else if(arg0.getSource() == chckbxCompleted || arg0.getSource() == chckbxPinned)
		{
			reloadDataFromTaskManagerBridge();						
		}
		else
		{
			throw new RuntimeException("Can't handle object " + arg0);
		}
	}

	private void doSave()
	{
		try {
			taskManagerBridge.saveTaskData(lastUsedSaveFile);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this,
				    e.getMessage(),
				    "Save Error",
				    JOptionPane.ERROR_MESSAGE);		
		}
	}
	
	private void doSaveAs()
	{
		if(!lastUsedSaveLoadDir.exists())
			lastUsedSaveLoadDir.mkdir();
		JFileChooser chooseFile = new JFileChooser(lastUsedSaveLoadDir);
		chooseFile.setApproveButtonText("Save"); 
		chooseFile.addChoosableFileFilter(
				new FileFilter()
				{
				    public boolean accept(File f)
				    {
				        if(f.isDirectory())
				        {
				            return true;
				        }
				        return f.getName().endsWith(".activly");
				    }
				 
				    public String getDescription()
				    {
				        return "Activly files (*.activly)";
				    }					
				}
		);
		
		int ret = chooseFile.showOpenDialog(this);
		if(ret == JFileChooser.APPROVE_OPTION)
		{
			File f = chooseFile.getSelectedFile();
				
			try {
				taskManagerBridge.saveTaskData(f);
				lastUsedSaveLoadDir = f.getCanonicalFile();
				lastUsedSaveFile = f;
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this,
					    e.getMessage(),
					    "Save Error",
					    JOptionPane.ERROR_MESSAGE);		
			}
		}
		else
		{
			//Ignore
		}			
	}
	
	private void reloadDataFromTaskManagerBridge() {
		removeAllItemPanel2ListPanels();
		itemPanelListPanels.clear();
		itemPanelToItemPanelListPanel.clear();
//		itemPanelListPanels.repaint();
//		itemPanelToItemPanelListPanel.repaint();
		addItemPanel2ListPanel("Tasks");
		
		OrderBy orderBy = null;
		if(this.rdbtnName.isSelected())
		{
			orderBy = OrderBy.NAME;
		}
//		else if(this.rdbtnCategory.isSelected())
//		{
//			orderBy = OrderBy.CATEGORY;			
//		}
		else if(this.rdbtnTime.isSelected())
		{
			orderBy = OrderBy.TIME_TO_SPEND;						
		}
		else
		{
			throw new RuntimeException("No such option");
		}
		
		String searchTerm = null;
		if(!searchTextField.getText().trim().equals(""))
		{
			searchTerm = searchTextField.getText().trim();
		}
		List <Task> tasks;
		boolean showCompleted = chckbxCompleted.isSelected();
		if(chckbxPinned.isSelected())
		{
			tasks = taskManagerBridge.filterTasksWithPin(orderBy, searchTerm, showCompleted);
		}
		else
		{
			tasks = taskManagerBridge.filterTasks(orderBy, searchTerm, showCompleted);			
		}
		
		System.out.println("Filter produced " + tasks.size() + " tasks");
		for(Task task : tasks)
		{
			this.addTask("Tasks", task);
		}
		
		this.validate();
		this.doLayout();
		for(ItemPanel2ListPanel panel : itemPanelListPanels.values())
		{
			System.out.println("Panel has " + panel.getNumberOfItems());
			panel.repaint();
			panel.doLayout();
		}
	}

	@Override
	public void taskUpdated(ItemPanel2 ip2) {
		if(detailsPanel.getCurrentTask() == ip2.getTask())
		{
			detailsPanel.resetDataFromTask();
		}
	}

	@Override
	public void taskDeleted(ItemPanel2 ip2, Task task) {
		taskManagerBridge.deleteTask(task);
		reloadDataFromTaskManagerBridge();
	}

	@Override
	public void taskEdited(ItemPanel2 ip2, Task task, TaskData taskData) {
		try
		{
			taskManagerBridge.editTask(task, taskData);
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(this,
				    e.getMessage(),
				    "Edit Error",
				    JOptionPane.ERROR_MESSAGE);					
		}
		reloadDataFromTaskManagerBridge();
	}

	@Override
	public void taskCompletedToggle(ItemPanel2 itemPanel2, Task task) {
		taskManagerBridge.toggleTaskCompleted(task);
		reloadDataFromTaskManagerBridge();
	}

	
	
}
